
innerapp.controller('server_config_Ctrl', ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) {
    $scope.currentGateway = null;
    $scope.retainedTypes = [{ID:1,Name:"不保留"},{ID:2,Name:"保留"}];
    var oldItem = { ClientName: "", HostPort: 0, Protocol: -1, Retained: -1};
    var userName = $cookies.get("userName");//"lossage"

    if (typeof (userName) != "string") {
        userName = "";
        alert("用户信息错误");
    }
    $http.get("/Service/gsm/getGateways/?user=" + userName)
        .then(function (result) {
            $scope.gateways = result.data;
            if ($scope.gateways.length > 0)
                $scope.toggle($scope.gateways[0]);
            else
                $scope.addOne();
        });
    $http.get("/Service/gsm/getProtocols/")
        .then(function (result) {
            $scope.ptypes = result.data;
        });
    $scope.toggle = function (item, isalert = true) {
        if (item == $scope.currentGateway)
            return;
        if (oldItem.Protocol != -1 && $scope.currentGateway != null && $scope.tcpCfg != null) {
            if (oldItem.ClientName != $scope.currentGateway.ClientName || oldItem.HostPort != $scope.tcpCfg.HostPort || oldItem.Protocol != $scope.tcpCfg.Protocol) {
                if (isalert) {
                    alert("未保存的数据将会丢弃");
                }
                $scope.currentGateway.ClientName = oldItem.ClientName;
            }
        }
        $scope.currentGateway = item;

        if (typeof (item.MasterID) == "undefined") {
            $scope.tcpCfg = { HostPort: 502, Protocol: 1 };
            oldItem.ClientName = item.ClientName;
            oldItem.HostPort = $scope.tcpCfg.HostPort;
            oldItem.Protocol = $scope.tcpCfg.Protocol;
            return
        }
        $http.get("/Service/gsm/getGatewayTCP/?key=" + item.MasterID)
            .then(function (result) {
                $scope.tcpCfg = result.data;
                if (item != null) {
                    oldItem.ClientName = item.ClientName;
                }
                if ($scope.tcpCfg != null) {
                    oldItem.HostPort = $scope.tcpCfg.HostPort;
                    oldItem.Protocol = $scope.tcpCfg.Protocol;
                }
            });
    };
    /*$scope.ptypes = [
        { dis: "ModbusRTU转ModbusTCP", value: 1 },
        { dis: "ModbusRTU原始报文", value: 2 },
        { dis: "不启用", value: 3 }]*//*
    $scope.importClick = function () {
        var file = document.getElementById("fileUpload").files[0];
        var reader = new FileReader();
        reader.onload = function (event) {
            try {
                var jsonResult = eval("(" + event.target.result + ")");
                if (jsonResult.mqtt_server == null || jsonResult.mqtt_server == undefined) {
                    return;
                }
                if (jsonResult != null && jsonResult != undefined && jsonResult.clients != null && jsonResult.clients != undefined && jsonResult.clients.length > 0) {
                    for (var i = 0; i < jsonResult.clients.length; i++) {
                        if ($scope.gateways != null) {
                            var client = jsonResult.clients[i];
                            if (client == null || client == undefined) {
                                continue;
                            }
                            if (client.name == null || client.name == undefined) {
                                continue;
                            }
                            if (checkExist(client.name)) {
                                alert("已存在" + client.name);
                                continue;
                            }
                            if (client.mqtt_client == null || client.mqtt_client == undefined) {
                                continue;
                            }
                            if (client.tcp_client == null || client.tcp_client == undefined) {
                                continue;
                            }
                            if (client.mqtt_client.use_topic_tip) {
                                client.mqtt_client.pub = jsonResult.mqtt_server.topic_tip + "-" + client.mqtt_client.pub;
                                client.mqtt_client.sub = jsonResult.mqtt_server.topic_tip + "-" + client.mqtt_client.sub;
                            }
                            if (client.mqtt_client.auto_add_machine_name) {
                                client.mqtt_client.pub = client.name + "-" + client.mqtt_client.pub;
                                client.mqtt_client.sub = client.name + "-" + client.mqtt_client.sub;
                            }
                            var gatewayConfig = {
                                ClientName: client.name,
                                PubTopic: client.mqtt_client.pub,
                                SubTopic: client.mqtt_client.sub,
                            }
                            var tcpConfig = { HostPort: client.tcp_client.port };
                            switch (client.tcp_client.protocol) {
                                case "MODBUS_RTU_2_TCP":
                                    tcpConfig.Protocol = 3;
                                    break;
                                case "NONE":
                                    tcpConfig.Protocol = 4;
                                    break;
                                default:
                                    tcpConfig.Protocol = 4;
                                    break;
                            }
                            $scope.gateways.unshift(gatewayConfig);
                            $scope.tcpCfg = tcpConfig;
                            //$scope.toggle($scope.gateways[0], false);
                            //$scope.saveConfig();
                            importSave(gatewayConfig, tcpConfig);
                            //break;
                        }
                    }
                }
            } catch (err) {
                alert("读入的文件有错误");
            }
        };
        reader.readAsText(file);
    };*//*
    function importSave(gateway, tcp) {
        $http.post("/Service/gsm/importSettings/", { tCP: tcp, gateway: gateway, user: userName }).
            then(function (data) {
                if (data.data.indexOf("Success") > -1) {
                    oldItem.ClientName = gateway.ClientName;
                    console.log("保存成功");
                } else {
                    console.log("保存失败");
                }
                $http.get("/Service/gsm/getGateways/?user=" + userName)
                    .then(function (result) {
                        $scope.gateways = result.data;
                        if ($scope.gateways.length > 0)
                            $scope.toggle($scope.gateways[0],false);
                    });
                //$scope.$apply();
            }, function (err) {
                console.log(err);
                //错误代码
            });
    }*/
    function checkExist(itemName, repeatTimes = 1) {
        repeatCount = 0
        $scope.gateways.forEach(element => {
            if (element.ClientName == itemName) {
                repeatCount ++;
                if(repeatCount >= repeatTimes)
                    return true;
            }
        });
        return false;
    }
    $scope.saveConfig = function () {
        if(checkExist($scope.currentGateway.ClientName,2)){            
            alert("设备名重复");
            return;
        }
        if (($scope.gateways != null && $scope.gateways.length > 0 && oldItem.Protocol == -1) || $scope.currentGateway == null || $scope.tcpCfg == null) {
            alert("没有修改有效设备参数");
            return;
        }
        if ($scope.currentGateway.ClientName == "" || $scope.currentGateway.ClientName == "undefined") {
            alert("没有输入设备名称")
            return;
        }
        if (typeof ($scope.currentGateway.MasterID) == "undefined") {
            if(checkExist($scope.currentGateway.ClientName,1)){            
                alert("设备名重复");
                return;
            }
            $http.post("/Service/gsm/saveConfig/?target=new_tcp", $scope.tcpCfg).
                then(function (data) {
                    $scope.tcpCfg = data.data
                    tempMasterID = data.data.UUID;
                    $http.post("/Service/gsm/saveConfig/?target=new_mqtt&masterid=" + data.data.UUID, $scope.currentGateway).
                        then(function (data2) {
                            if((typeof(data2.data)=='string') && ((data2.data.indexOf("error") > 0)||(data2.data.indexOf("Failed") > 0))){
                                alert("保存失败:" + data2.data);
                                return;
                            }
                            for (var i = 0; i < $scope.gateways.length; i++) {
                                if ($scope.gateways[i] == $scope.currentGateway) {
                                    $scope.gateways[i] = data2.data;
                                    break;
                                }
                            }
                            //$scope.currentGateway = data2.data;
                            $http.post("/Service/gsm/saveConfig/?target=usermqtt&user=" + userName + "&uuid=" + data2.data.UUID, { UUID: data.data.UUID }).
                                //$http.post("/Service/gsm/saveConfig/?target=usermqtt&user=" + userName + "&uuid=" + data.data.UUID, $scope.currentGateway).
                                then(function (data3) {
                                    if (data3.data.indexOf("Success") > -1) {
                                        oldItem.ClientName = $scope.currentGateway.ClientName;
                                        oldItem.Retained = $scope.currentGateway.Retained;
                                        oldItem.Protocol = $scope.tcpCfg.Protocol;
                                        oldItem.HostPort = $scope.tcpCfg.HostPort;
                                        alert("保存成功");
                                    } else {
                                        alert("保存失败")
                                    }
                                }, function (err) {
                                    console.log(err);
                                    //错误代码
                                });
                        }, function (err) {
                            console.log(err);
                            //错误代码
                        });
                }, function (err) {
                    console.log(err);
                    //错误代码
                });
            return;
        }

        if (oldItem.HostPort != $scope.tcpCfg.HostPort || oldItem.Protocol != $scope.tcpCfg.Protocol || oldItem.Retained != $scope.currentGateway.Retained) {
            $http.post("/Service/gsm/saveConfig/?target=tcp", $scope.tcpCfg).
                then(function (data) {
                    if (data.data.indexOf("Success") > -1) {
                        oldItem.Protocol = $scope.tcpCfg.Protocol;
                        oldItem.HostPort = $scope.tcpCfg.HostPort;
                        if (oldItem.ClientName != $scope.currentGateway.ClientName || oldItem.Retained != $scope.currentGateway.Retained) {
                            $http.post("/Service/gsm/saveConfig/?target=mqtt", $scope.currentGateway).
                                then(function (data2) {
                                    if (data2.data.indexOf("Success") > -1) {
                                        oldItem.ClientName = $scope.currentGateway.ClientName;
                                        alert("保存成功");
                                    } else {
                                        alert("保存失败")
                                    }
                                }, function (err) {
                                    console.log(err);
                                    //错误代码
                                });
                        }
                        else {
                            alert("保存成功");
                        }
                    }
                }, function (err) {
                    console.log(err);
                });
        }
    };
    //var i = 1;
    $scope.removeOne = function () {
        if ($scope.currentGateway != null) {
            if (typeof ($scope.currentGateway.UUID) == "undefined") {
                var index = -1;
                var item = $scope.currentGateway;
                for (var i = 0; i < $scope.gateways.length; i++) {
                    if ($scope.gateways[i] == item) {
                        index = i;
                        break;
                    }
                }
                if (index >= 0) {
                    $scope.gateways.splice(index, 1);
                }
                if (index == 0) {
                    $scope.toggle($scope.gateways[0]);
                } else {
                    $scope.toggle($scope.gateways[i - 1]);
                }
                alert("删除成功");
                return;
            }
            $http.get("/Service/gsm/removeItem/?key=" + $scope.currentGateway.UUID)
                .then(function (result) {
                    if (result.data.indexOf("Success") > -1) {
                        alert("删除成功");
                        var index = -1;
                        var item = $scope.currentGateway;
                        for (var i = 0; i < $scope.gateways.length; i++) {
                            if ($scope.gateways[i] == item) {
                                index = i;
                                break;
                            }
                        }
                        if (index >= 0) {
                            $scope.gateways.splice(index, 1);
                        }
                        if (index == 0) {
                            $scope.toggle($scope.gateways[0]);
                        } else {
                            $scope.toggle($scope.gateways[i - 1]);
                        }
                    }
                    else
                        alert("删除失败")
                });
        }
    };
    $scope.addOne = function () {
        if ($scope.gateways != null) {
            var index = $scope.gateways.unshift({ ClientName: "新建网关" });
            $scope.toggle($scope.gateways[0]);
        }
        //$scope.gateways[$scope.gateways.length] = {ClientName="未命名"}
        //$scope.tcpCfg = {HostPort = 502, Protocol = 1}
        /*$http.get("/Service/gsm/addItem/")
            .then(function (result) {
                //$scope.ptypes = result.data;
            });*/
    };
}]);